package com.heima.media.task;

import com.alibaba.fastjson.JSON;
import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class MediaTasks {
    // 注入redisson客户端
    @Autowired
    private RedissonClient client;

    @Autowired
    private IAuditService auditService;

    @Async
    public void handleMessage() {
        try {
            // 获取一个阻塞队列,指定队列的名称
            RQueue<String> queue = client.getBlockingQueue("article-publish");
            // 发送一个初始化消息
            // 获取延迟队列
            RDelayedQueue<String> delayedQueue = client.getDelayedQueue(queue);
            delayedQueue.offer("init", 1, TimeUnit.SECONDS);
            // 拉取消息
            while (true) {
                String msg = ((RBlockingQueue<String>) queue).poll(1, TimeUnit.MINUTES);
                if (!StringUtils.isEmpty(msg) && !msg.equals("init")) {
                    System.out.println("接收到消息: " + msg + " " + new Date());
                    // 执行文章的发布
                    WmNews wmNews = JSON.parseObject(msg, WmNews.class);
                    auditService.audit(wmNews);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
